<template>
  <div class="drawer-main">
    <el-drawer
      ref="drawerMain"
      :title="drawerTitle"
      :visible.sync="drawer"
      direction="rtl"
      size="63%"
      :wrapperClosable="false"
      @closed="handleClose"
    >
      <div class="drawer-content">
        <div class="detail-info-main">
          <div class="info-main">
            <div class="info-item">
              <span class="info-label">{{ $i18n.t("bomBuyer.materialName") }}：</span>
              <span class="info-text">{{ materialName||'-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">{{ $i18n.t("bomBuyer.bomVin") }}：</span>
              <span class="info-text">{{ vinCode||'-' }}</span>
            </div>
            <div class="info-item">
              <p class="info-label link" @click="showImgViewer">{{ $i18n.t("bomBuyer.picture") }}</p>
              <!-- <span class="info-text">{{ masterDetail.createTime||'-' }}</span> -->
            </div>
          </div>
        </div>
        <template>
          <p class="materialType-title">原厂件</p>
          <ele-form
            ref="validateForm0"
            key="validateForm0"
            :disabled="disabled"
            v-model="isProvideFormData[0]"
            v-bind="isProvideFormConfig"
          >
          </ele-form>
          <div class="form-section" v-if="isProvideFormData[0].isProvide !== 0">
            <div 
             v-for="(formData, index) in originalPartsFormData" 
             :class="`form-div ${index == 0 ? 'form-div-first-child' : ''}`" 
             :key="'originalFormData' + index"
            >
              <ele-form
                :ref="`validateForm${'1'+ index}`"
                :key="'originalForm' + index"
                :disabled="disabled"
                v-model="originalPartsFormData[index]"
                v-bind="originalPartsFormConfig"
              >
              </ele-form>
            </div>
          </div>
        </template>

        <template >
          <p class="materialType-title">品质件</p>
          <div class="form-section">
            <i @click="addItem(2)" v-if="operateType === 0" class="el-icon-circle-plus-outline icon-position"></i>
            <ele-form
              ref="validateForm1"
              key="validateForm1"
              :disabled="disabled"
              v-model="isProvideFormData[1]"
              v-bind="isProvideFormConfig"
            >
            </ele-form>
          </div>
          <div class="form-section" v-if="isProvideFormData[1].isProvide !== 0">
            <div 
             v-for="(formData, index) in qualityPartsFormData" 
             :class="`form-div ${index == 0 ? 'form-div-first-child' : ''}`" 
             :key="'qualityFormData' + index"
            >
              <i 
                @click="deleteItem(2, index)"
                v-if="index !== 0 && operateType === 0" 
                class="el-icon-remove-outline icon-position">
              </i>
              <ele-form
                :ref="`validateForm${'2'+ index}`"
                :key="'qualityForm' + index"
                :disabled="disabled"
                v-model="qualityPartsFormData[index]"
                v-bind="index == 0 ? qualityPartsFormConfig : qualityPartsFormAddConfig"
              >
              </ele-form>
            </div>
          </div>
        </template>

        <template>
          <p class="materialType-title">拆车件</p>
          <ele-form
            ref="validateForm3"
            key="validateForm3"
            :disabled="disabled"
            v-model="isProvideFormData[3]"
            v-bind="isProvideFormConfig"
          >
          </ele-form>
          <div class="form-section" v-if="isProvideFormData[3].isProvide !== 0">
            <div 
             v-for="(formData, index) in dismantlingPartsFormData" 
             :class="`form-div ${index == 0 ? 'form-div-first-child' : ''}`" 
             :key="'dismantlingPartsFormData' + index"
            >
              <ele-form
                :ref="`validateForm${'4'+ index}`"
                :key="'dismantlingForm' + index"
                :disabled="disabled"
                v-model="dismantlingPartsFormData[index]"
                v-bind="dismantlingPartsFormConfig"
              >
              </ele-form>
            </div>
          </div>
        </template>

        <template >
          <p class="materialType-title">其他</p>
          <div class="form-section">
            <i @click="addItem(3)" v-if="operateType === 0" class="el-icon-circle-plus-outline icon-position"></i>
            <ele-form
              ref="validateForm2"
              key="validateForm2"
              :disabled="disabled"
              v-model="isProvideFormData[2]"
              v-bind="isProvideFormConfig"
            >
            </ele-form>
          </div>
          <div class="form-section" v-if="isProvideFormData[2].isProvide !== 0">
            <div :class="`form-div ${index == 0 ? 'form-div-first-child' : ''}`" v-for="(formData, index) in othersFormData" :key="'formData' + index">
              <i 
                @click="deleteItem(3,index)"
                v-if="index !== 0 && operateType === 0" 
                class="el-icon-remove-outline icon-position">
              </i>
              <ele-form
                :ref="`validateForm${'3'+ index}`"
                :key="'form' + index"
                :disabled="disabled"
                v-model="othersFormData[index]"
                v-bind="index == 0 ? othersFormConfig : othersFormAddConfig"
              >
              </ele-form>
            </div>
          </div>
        </template>
      </div>
      <div class="btns" v-if="operateType == 0">
        <el-button @click="quit">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-drawer>
    <el-image-viewer
      v-if="showViewer"
      :zIndex='99999'
      :on-close="closeViewer"
      :url-list="showViewerImages"
      :initialIndex="initialIndex"
    />
  </div>
</template>
<script>
import { formDescDialogMinxin } from './drawerConfig'
import { mesPcQuotationSave, mesPcQuotationResult } from '@/api/materials/supplier.js'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
export default {
  mixins: [formDescDialogMinxin],
  components: {
    ElImageViewer
  },
  data() {
    const self = this;
    return {
      detailId: null,
      vinCode: '',
      materialName: '',
      materialPhotoUrl: '',
      operateType: 0,
      drawer: false,
      roleData: [],
      showViewer: false,
      initialIndex: 0,
      showViewerImages: [
        'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
        'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg'
      ],
      isProvideFormData: [{},{},{},{}],
      originalPartsFormData: [{}],
      dismantlingPartsFormData: [{}],
      qualityPartsFormData: [{}],
      othersFormData: [{}],
    }
  },
  props: {
    // detailId: {
    //   type: Number | null,
    //   default: null
    // },
    // operateType: {
    //   type: Number,
    //   default: 0,
    // },
    materialNum: {
      type: Number,
      default: 0,
    }
  },
  watch: {
    materialNum: {
      handler(val) {
        this.originalPartsFormData.forEach(ele => {ele.num = val})
        this.qualityPartsFormData.forEach(ele => {ele.num = val})
        this.othersFormData.forEach(ele => {ele.num = val})
      },
      immediate: true
    }
  },
  computed: {
    drawerTitle() {
      return this.operateType ? $i18n.t('supplier.viewQuotation') : $i18n.t('supplier.quotation') 
    },
    disabled() {
      return this.operateType ? true : false
    },
  },
  mounted() {
    
  },
  methods: {
    //关闭图片预览弹框
    closeViewer() {
      this.showViewer = false
      this.initialIndex = 0
    },
    //图片预览展示
    showImgViewer() {
      this.showViewer = true
      this.showViewerImages = this.materialPhotoUrl?.split(',') || []
    },
    showDrawer() {
      this.drawer = true
      if(this.operateType == 1) {
        this.getDetails()
      }
    },
    getDetails() {
      mesPcQuotationResult({demandId: this.detailId}).then(res => {
        if(res.data.code == 0) {
          let dataArr = res.data.result
          dataArr.forEach(ele => {
            if(ele.materialType == 1) {
              if(ele.quotationList && ele.quotationList.length && ele.quotationList[0].isProvide) {
                this.$set(this.isProvideFormData, 0, {
                  isProvide: 1
                })
              } else {
                this.$set(this.isProvideFormData, 0, {
                  isProvide: 0
                })
              }
              this.originalPartsFormData = ele.quotationList.map(ele => {
                return {
                  ...ele,
                  materialUnit: this.materialDetail.materialUnit,
                  brand: this.materialDetail.materialBrand,
                  pictureList: ele.pictureList.length ? ele.pictureList.map(e => {
                    return {path: e, src: e}
                  }) : []
                }
              })
            }

            if(ele.materialType == 2) {
              if(ele.quotationList && ele.quotationList.length && ele.quotationList[0].isProvide) {
                this.$set(this.isProvideFormData, 1, {
                  isProvide: 1
                })
              } else {
                this.$set(this.isProvideFormData, 1, {
                  isProvide: 0
                })
              }
              this.qualityPartsFormData = ele.quotationList.map(ele => {
                return {
                  ...ele,
                  materialUnit: this.materialDetail.materialUnit,
                  brand: this.materialDetail.materialBrand,
                  pictureList: ele.pictureList.length ? ele.pictureList.map(e => {
                    return {path: e, src: e}
                  }) : []
                }
              })
            }

            if(ele.materialType == 3) {
              if(ele.quotationList && ele.quotationList.length && ele.quotationList[0].isProvide) {
                this.$set(this.isProvideFormData, 2, {
                  isProvide: 1
                })
              } else {
                this.$set(this.isProvideFormData, 2, {
                  isProvide: 0
                })
              }
              this.othersFormData = ele.quotationList.map(ele => {
                return {
                  ...ele,
                  pictureList: ele.pictureList.length ? ele.pictureList.map(e => {
                    return {path: e, src: e}
                  }) : []
                }
              })
            }
            if(ele.materialType == 4) {
              if(ele.quotationList && ele.quotationList.length && ele.quotationList[0].isProvide) {
                this.$set(this.isProvideFormData, 3, {
                  isProvide: 1
                })
              } else {
                this.$set(this.isProvideFormData, 3, {
                  isProvide: 0
                })
              }
              this.dismantlingPartsFormData = ele.quotationList.map(ele => {
                return {
                  ...ele,
                  pictureList: ele.pictureList.length ? ele.pictureList.map(e => {
                    return {path: e, src: e}
                  }) : []
                }
              })
            }

          })
        }
      })
    },
    addItem(type) {
      let deleteData = null
      if(type === 2) {
        deleteData = this.qualityPartsFormData
      } else if(type === 3) {
        deleteData = this.othersFormData
      }
      deleteData.push({num: this.materialNum})
    },
    deleteItem(type, index) {
      let deleteData = null
      if(type === 2) {
        deleteData = this.qualityPartsFormData
      } else if(type === 3) {
        deleteData = this.othersFormData
      }
      deleteData.splice(index, 1)
    },
    quit() {
      this.isProvideFormData = [{},{},{},{}]
      this.originalPartsFormData = [{num: this.materialNum}]
      this.qualityPartsFormData = [{num: this.materialNum}]
      this.othersFormData = [{num: this.materialNum}]
      this.dismantlingPartsFormData = [{num: this.materialNum}]
      this.drawer = false
    },
    // 验证所有组件的内置验证方法
    validateComponent() {
      let allForm = []
      this.isProvideFormData.forEach((ele, index) => {
        allForm.push(this.$refs[`validateForm${index}`])
      })
      this.originalPartsFormData.forEach((ele, index) => {
        allForm.push(this.$refs[`validateForm${'1' + index}`][0])
      })
      this.qualityPartsFormData.forEach((ele, index) => {
        allForm.push(this.$refs[`validateForm${'2' + index}`][0])
      })
      this.othersFormData.forEach((ele, index) => {
        allForm.push(this.$refs[`validateForm${'3' + index}`][0])
      })
      this.dismantlingPartsFormData.forEach((ele, index) => {
        allForm.push(this.$refs[`validateForm${'4' + index}`][0])
      })

      console.log('forms', allForm)
      const validators = allForm.filter(form => form)
        .map((form) => form.validateForm)
        .filter(Boolean);
      console.log('validators', validators)

      return Promise.all(validators.map((fn) => fn()));
    },
    createSubmitData() {
      let data = []
      if(this.isProvideFormData[0].isProvide) {
        this.originalPartsFormData.forEach(ele => {
          data.push({
            "detailId": this.detailId,
            "materialType": 1,
            ...ele,
            isProvide: 1,
            "pictureList": (ele.pictureList && ele.pictureList.length) ? ele.pictureList.map(ele => ele.path) : []
          })
        })
      } else {
        data.push({
          "detailId": this.detailId,
          "materialType": 1,
          isProvide: 0,
          "pictureList": []
        })
      }
      if(this.isProvideFormData[1].isProvide) {
        this.qualityPartsFormData.forEach(ele => {
          data.push({
            "detailId": this.detailId,
            "materialType": 2,
            ...ele,
            isProvide: 1,
            "pictureList": (ele.pictureList && ele.pictureList.length) ? ele.pictureList.map(ele => ele.path) : []
          })
        })
      } else {
        data.push({
          "detailId": this.detailId,
          "materialType": 2,
          isProvide: 0,
          "pictureList": []
        })
      }
      
      if(this.isProvideFormData[2].isProvide) {
        this.othersFormData.forEach(ele => {
          data.push({
            "detailId": this.detailId,
            "materialType": 3,
            ...ele,
            isProvide: 1,
            "pictureList": (ele.pictureList && ele.pictureList.length) ? ele.pictureList.map(ele => ele.path) : []
          })
        })
      } else {
        data.push({
          "detailId": this.detailId,
          "materialType": 3,
          isProvide: 0,
          "pictureList": []
        })
      }
      if(this.isProvideFormData[3].isProvide) {
        this.originalPartsFormData.forEach(ele => {
          data.push({
            "detailId": this.detailId,
            "materialType": 4,
            ...ele,
            isProvide: 1,
            "pictureList": (ele.pictureList && ele.pictureList.length) ? ele.pictureList.map(ele => ele.path) : []
          })
        })
      } else {
        data.push({
          "detailId": this.detailId,
          "materialType": 4,
          isProvide: 0,
          "pictureList": []
        })
      }
      
      console.log(data)
      return data
    },
    handleSubmit() {
      this.validateComponent().then(res => {
        let data = this.createSubmitData()
        mesPcQuotationSave(data).then(res => {
          if(res.data.code == 0) {
            this.$message.success(this.$t("common.submitSuccess"))
            this.$emit('updateList')
            this.drawer = false
          } else {
            this.$message.error(res.data.message)
          }
        })
      }).catch(err => {
        console.log(err)
      })
    },
    clearDialog() {
      this.quit()
    },
    handleClose() {
      this.quit()
    }
  }
}
</script>
<style lang="scss" scoped>
.drawer-main {
  /deep/.el-drawer__body {
    padding: 0 20px;
  }
  .info-main {
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 20px;
    .info-item {
      width: 40%;
      display: flex;
      margin-bottom: 10px;
      font-size: 14px;
      text-align: center;
      .link {
        width: 100%;
        text-align: center;
        cursor: pointer;
        color: #0066ff;
      }
    }
    .item-full {
      width: 100%;
    }
  }
}
.materialType-title {
  font-weight: bold;
  line-height: 30px;
  padding-left: 20px;
  background-color: #ddd;
  margin-bottom: 10px;
}
.form-section {
  width: 100%;
  position: relative;
  
  .form-div {
    position: relative;
    border-top: solid 2px #ccc;
    padding-top: 40px;
  }
  .form-div-first-child {
    border-top: none;
    padding-top: 0;
  }
  .icon-position {
    position: absolute;
    top: 6px;
    right: 0;
    color: #0066ff;
    font-size: 20px;
    cursor: pointer;
    z-index: 9999;
  }
}
.detail-info-main {
  .info-main {
    display: flex;
    flex-wrap: nowrap;
    .info-item {
      text-align: center;
      width: 33%;
      font-size: 14px;
      .info-label {
        padding-right: 2px;
      }
    }
  }
}
.btns {
  margin: 20px 0;
  text-align: right;
}
</style>